package com.westcom.healthmate.service.impl;

import com.alibaba.fastjson.JSON;
import com.westcom.healthmate.bean.FramewareInfoBean;
import com.westcom.healthmate.common.exception.ErrorException;
import com.westcom.healthmate.common.utils.CommonUtils;
import com.westcom.healthmate.service.FramewareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class FramewareServiceImpl implements FramewareService
{
    @Autowired
    private Environment env;
    @Override
    public FramewareInfoBean getFramewareInfo(int versionCode) throws ErrorException
    {

        List<FramewareInfoBean> infos = getAllFramewareInfos();
        if(CollectionUtils.isEmpty(infos))
        {
            return null;
        }
        if(versionCode <0)
        {
            FramewareInfoBean res = infos.get(0);
            int latestVersionCode = res.getVersionCode();
            for(FramewareInfoBean info:infos)
            {
                if(info.getVersionCode() >latestVersionCode)
                {
                    res = info;
                    latestVersionCode = res.getVersionCode();
                }
            }
            return res;
        }else
        {
            for(FramewareInfoBean info:infos)
            {
                if(info.getVersionCode() == versionCode)
                {
                    return info;
                }
            }
        }
        return null;
    }

    @Override
    public List<FramewareInfoBean> getAllFramewareInfos() throws  ErrorException
    {
        byte[] framewareInfos = CommonUtils.readFile(env.getProperty("frameware.infos.path"));
        List<FramewareInfoBean> infos = JSON.parseArray(new String(framewareInfos),FramewareInfoBean.class);
        return infos;
    }
}

